package com.xapp.utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.xapp.yhjsBirdge.BridgeHandler;
import com.xapp.yhjsBirdge.BridgeWebView;
import com.xapp.yhjsBirdge.CallBackFunction;

import java.util.HashMap;
import java.util.Map;

/**
 * @author YH_CK
 * @data 2018.09.14 13:58
 * @describe 注册JS调用方法
 **/
public class RegisterFucUtils {

    private static final String TAG = RegisterFucUtils.class.getSimpleName();
    private  RegisterFucUtils instance = null;
    private  Context mContext;
    private  Handler mHandler;
    private Map<String, CallBackFunction> callBackFucMap;

//    public RegisterFucUtils getInstance(Context context, Handler handler) {
//        this.instance = new RegisterFucUtils();
//        this.mContext = context;
//        this.mHandler = handler;
//        return instance;
//    }

    public RegisterFucUtils(Context context, Handler handler) {
        this.callBackFucMap = new HashMap<>();
        this.mContext = context;
        this.mHandler = handler;

    }

    public CallBackFunction getCallBackFunction(String key) {
        return this.callBackFucMap.get(key);
    }

    /*
     * Js调用Java方法并传递数据
     * 必须和js同名函数，注册具体执行函数，类似java实现类
     * 第一参数是订阅的java本地函数名字 第二个参数是回调Handler
     * 参数返回js请求的resqustData,function.onCallBack（）回调到js，调用function(responseData)
     * */
    public void registerJSFunction(BridgeWebView webView, final String handlerName, final int messageCode) {
        webView.registerHandler(handlerName, new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i(TAG, handlerName + "-HTTP-Data-from-web = " + data);
                callBackFucMap.put(handlerName, function);
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("data", data);
                message.what = messageCode;
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
        });
    }
}
